// Copyright 2011 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

/**
 * @fileoverview Defines XMLHttpRequest functionality within the Chrome portion
 * of Firefox.
 *
 * @author jasonstredwick@google.com (Jason Stredwick)
 */


goog.provide('mimic.xhr');


/**
 * Requests the file specified with the given url; can be local or remote.
 * @param {string} url The url of the file.
 * @param {string} mimeTypeOverride The mime type preferred if not the default.
 * @return {!Object} The object {error: boolean, text: string} where the text
 *     is either the file contents or an error string.
 */
mimic.xhr.requestFile = function(url, mimeTypeOverride) {
  try {
    var Cc = Components.classes;
    var Ci = Components.interfaces;
    var component = '@mozilla.org/xmlextras/xmlhttprequest;1';
    var xhr = Cc[component].createInstance(Ci.nsIXMLHttpRequest);
    xhr.open('GET', url, false);

    if (mimeTypeOverride) {
      xhr.overrideMimeType(mimeTypeOverride);
    }

    try {
      xhr.send();
    } catch (error) {
      return {
        error: true,
        text: 'ERROR (mimic.xhr.requestFile): Exception: Url not found - ' +
              url};
    }

    // TODO (jasonstredwick): Lookup response values.  I believe status 0 means
    // local file (at least in firefox extensions.  Need to check and update
    // if necessary.
    if (xhr.status != 200 && xhr.status != 0) {
      return {
        error: true,
        text: 'ERROR (mimic.xhr.requestFile): Failed to load mimic ' +
              'extension manifest.json with status (' + xhr.status + ') and ' +
              'url - ' + url};
    }

    return {error: false, text: xhr.responseText};
  } catch (error) {
    return {
      error: true,
      text: 'ERROR (mimic.xhr.requestFile): General error - ' +
            error};
  }
};

